const app = getApp()

Page({

  data: {
    title: '',
    type: 'in_theaters',
    hasMore: true,
    page: 1,
    size: 20,
    movies: []
  },
  loadMore() {
    if (!this.data.hasMore) return

    wx.showLoading({
      title: '拼命加载中...'
    })

    return app.douban.find(this.data.type, this.data.page++, this.data.size)
      .then(d => {
        if (d.subjects.length) {
          this.setData({
            movies: this.data.movies.concat(d.subjects)
          })
        } else {
          this.setData({
            hasMore: false
          })
        }
        wx.hideLoading()
      })
      .catch(e => {
        console.error(e)
        wx.hideLoading()
      })
  },
  onLoad(params) {
    params = {
      "type": "in_theaters",
      "title": "正在上映的电影-苏州"
    }
    // {"type":"coming_soon","title":"即将上映的电影"}
    // { "type":"new_movies", "title":"豆瓣电影新片榜" }

    this.data.title = params.title || this.data.title
    this.data.type = params.type || this.data.type

    this.loadMore()
  },
  onPullDownRefresh() {
    this.setData({
      movies: [],
      page: 1,
      hasMore: true
    })
    this.loadMore()
      .then(() => wx.stopPullDownRefresh())
  },
  onReachBottom() {
    this.loadMore()
  }
})